package vma.nicici.chat;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import vma.nicici.chat.api.map.MapApi;
import vma.nicici.chat.api.map.Marker;
import vma.nicici.chat.api.map.Point;
import vma.nicici.chat.api.photos.PhotosDb;
import vma.nicici.chat.communication.AsynchCallback;
import vma.nicici.chat.gson.FbUserInfo;
import vma.nicici.chat.gson.Message;
import vma.nicici.chat.history.HistoryDatabase;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

public class MsgDetailActivity extends Activity {

	private static final String DATE_FORMAT = "yyyy-MM-dd'T'hh:mm:ssZZZZZ";
	private Message msg;
	private final MapApi map = new MapApi(15, 500, 500);

	ImageView mapView;
	TextView msgDetail;
	TextView userInfo;
	TextView link;
	ImageView userPhoto;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		hideUpperBar();
		setContentView(R.layout.activity_msg_detail);
		Bundle extras = getIntent().getExtras();
		msg = (Message) extras.get("msg");

		chainedSetup();
	}

	private void chainedSetup() {
		initUI();
		prepareMap();
		preparePhoto();
		prepareUserDetails();

	}

	private void hideUpperBar() {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	}

	private void initUI() {
		mapView = (ImageView) findViewById(R.id.mapImageView);
		userInfo = (TextView) findViewById(R.id.userDetails);
		userPhoto = (ImageView) findViewById(R.id.userPhoto);
		msgDetail = (TextView) findViewById(R.id.msgDetails);
		link = (TextView) findViewById(R.id.twLink);
	}

	private void prepareMap() {
		if (msg.lat == -1 || msg.lon == -1)
			return;

		Point center = Point.fromDouble(msg.lat, msg.lon);
		map.setCenter(center);
		map.addMarker(new Marker("red", "X", center));

		map.getMapAsynch(new AsynchCallback<Bitmap>() {
			@Override
			public void onFinished(final Bitmap response) throws IOException,
					URISyntaxException {

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mapView.setImageBitmap(response);
					}
				});

			}
		});
	}

	private void preparePhoto() {
		PhotosDb.instance(this).getPhotoFromMessageAsynch(msg,
				new AsynchCallback<Bitmap>() {
					@Override
					public void onFinished(final Bitmap response)
							throws IOException, URISyntaxException {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								userPhoto.setImageBitmap(response);
							}
						});
					}
				});
	}

	private void prepareUserDetails() {
		userInfo.setText(getString(R.string.working));

		HistoryDatabase.getInstance().getFbUserAsynch(msg.facebookUserID,
				new AsynchCallback<FbUserInfo>() {
					@Override
					public void onFinished(final FbUserInfo response)
							throws IOException, URISyntaxException {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								userInfo.setText(response.name);
								if (! (response.link == null || response.link == "" || response.link.length() < 24 )) {									
									String linkToProfile = "<a href=\""+response.link+"\">View Profile</a>";								
									link.setMovementMethod(LinkMovementMethod.getInstance());
									link.setText(Html.fromHtml(linkToProfile));
									Log.d("fb user: ", response.toString());
								}								
							}
						});
					}
				});
		
		String msgDetailtext =parseDate(msg.timestamp)+ "\nLatitude: " + msg.lat.toString().substring(0, Math.min(msg.lat.toString().length(), 5)) +
				"\nLongitude: " + msg.lon.toString().substring(0, Math.min(msg.lat.toString().length(), 5)) ;
		

		msgDetail.setText(msgDetailtext);
	}
	
	
	private String parseDate(String timestamp) {
		SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
		Calendar date = Calendar.getInstance();
		try {
			date.setTime(formatter.parse(timestamp));
		} catch (ParseException e) {
			return "bad timestamp!";
		}		
		String minute = "" + date.get(Calendar.MINUTE);
		if (minute.length() == 1 ) minute = "0"+minute;
		String parsedDate = "\nSent at " +
				+ date.get(Calendar.HOUR_OF_DAY) + ":" + minute + "\n" + date.get(Calendar.DAY_OF_MONTH) + ". " 
						+ new DateFormatSymbols().getMonths()[date.get(Calendar.MONTH)] + " " + date.get(Calendar.YEAR) ;
		return parsedDate;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_msg_detail, menu);
		return true;
	}

}
